package com.hanxiang.hankol.common;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.baselibrary.MessageBus;
import com.baselibrary.base.mvvm.BaseViewModel;
import com.baselibrary.bean.CommentEventBusBean;
import com.baselibrary.manager.DialogManager;
import com.baselibrary.manager.SensorsDataManager;
import com.baselibrary.utils.AppManager;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.GsonUtils;
import com.baselibrary.utils.KeyBoardUtils;
import com.baselibrary.utils.SpUtils;
import com.baselibrary.utils.ToastUtils;
import com.baselibrary.utils.emo.EmojiUtils;
import com.baselibrary.utils.emo.EmotionKeyboardSwitchHelper;
import com.baselibrary.utils.emo.adapter.EmojiGvAdapter;
import com.baselibrary.utils.emo.adapter.EmojiVpAdapter;
import com.hanxiang.hankol.R;
import com.hanxiang.hankol.databinding.ActivityAddCommentWindowRevisionBinding;
import com.okhttp.SendRequest;
import com.okhttp.callbacks.StringCallback;
import com.okhttp.comment.CommentBean;
import com.okhttp.comment.CommentConstant;
import com.okhttp.comment.CommentReplyBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.Call;
import okhttp3.Request;

/**
 * 弹窗类型的发表评论
 */

public class WindowAddCommentActivity extends AppCompatActivity {
    private static final String TAG = "Cannot ";
    private ActivityAddCommentWindowRevisionBinding mWindowBinding;//弹窗评论
    private int type = 0;  //评论类型 1评论的评论 4文章评论 5产品评论 6动态评论 7专栏评论 8话题评论 9话题动态评论 10 讲坛评论 11 课程评论
    private int typeId;
    private boolean flag = true;

    private Object dataBean;
    private String title;
    private String mContent;
    private int puId;
    private int pId;
    private Intent mIntent;
    private boolean isShowReply; // true 评论的评论  false 发表看法产生一个评论
    private EmotionKeyboardSwitchHelper mEmotionKeyboardSwitchHelper;
    private int keyboardHeight;
    private CommentEventBusBean mCommentEventBusBean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEmotionKeyboardSwitchHelper = EmotionKeyboardSwitchHelper.with(this);
        if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this);
        initContentView();
        mIntent = getIntent();
        if (mIntent.getExtras() != null) {
            type = mIntent.getExtras().getInt("type");
            typeId = mIntent.getExtras().getInt("typeId");
            mContent = mIntent.getExtras().getString(CommentConstant.COMMENT_CONTENT);
            isShowReply = mIntent.getExtras().getBoolean(CommentConstant.COMMENT_IS_VIOLATION);
            dataBean = mIntent.getExtras().getSerializable("dataBean");
            title = mIntent.getExtras().getString("title", "");
            pId = mIntent.getExtras().getInt("pId");
            puId = mIntent.getExtras().getInt("puId");


        }
        setViewData();
        initViewPager();
        //获取键盘高度
        keyboardHeight = KeyBoardUtils.getKeyboardHeight(this);
        mEmotionKeyboardSwitchHelper.bind(mWindowBinding.edContent, mWindowBinding.ivCommentEmoticon, mWindowBinding.flEmoji, keyboardHeight);
    }
    private void setViewData() {
        if (isShowReply) {
            if (dataBean != null) {
                if (dataBean instanceof CommentBean.DataBean.CommentInfoBean) {
                    mWindowBinding.edContent.setHint("回复 @" + ((CommentBean.DataBean.CommentInfoBean) dataBean).getUser().getName());
                } else if (dataBean instanceof CommentPager.DataBean) {
                    mWindowBinding.edContent.setHint("回复 @" + ((CommentPager.DataBean) dataBean).getUser().getName());
                }
            } else {
                mWindowBinding.edContent.setHint("回复 @" + title);
            }
        }
        if (!TextUtils.isEmpty(mContent)) {
            mWindowBinding.edContent.setText(mContent);
            mWindowBinding.edContent.setSelection(mContent.length());
            mWindowBinding.tvCommentSend.setVisibility(View.VISIBLE);
        }
        mWindowBinding.edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @SuppressLint({"ResourceType", "SetTextI18n"})
            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().trim().length() <= 0) {
                    mWindowBinding.tvCommentSend.setVisibility(View.GONE);
                } else {
                    mWindowBinding.tvCommentSend.setVisibility(View.VISIBLE);
                }

            }
        });

        mWindowBinding.tvCommentSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SpUtils.getInstance().getLoadUserBean().getData().getUserRank() == 99) {
                    AppManager.getAppManager().openLoginPage();
                    return;
                }
                KeyBoardUtils.hideSoftKeyboard(WindowAddCommentActivity.this);
                addComment(mWindowBinding.edContent);
            }
        });

        EmojiGvAdapter mOftenEmoAdapter = new EmojiGvAdapter(this, EmojiUtils.getOftenEmo(this));
        mWindowBinding.rvOftenEmo.setAdapter(mOftenEmoAdapter);
        mWindowBinding.rvOftenEmo.setOnItemClickListener((parent, view, position, id) -> {
            //获取选中的表情字符
            String emoji = (String) parent.getAdapter().getItem(position);
            mWindowBinding.edContent.append(emoji);
        });
    }

    private void addComment(EditText edContent) {
        String content = edContent.getText().toString();
        if (CommonUtil.isBlank(content)) {
            ToastUtils.showShort(WindowAddCommentActivity.this, "请输入");
            return;
        }
        if (!flag)
            return;
        flag = false;
        mWindowBinding.tvCommentSend.setEnabled(false);//设置【发送按钮不能点击，在网络回来之前】
        if (isShowReply) {
            Log.d(TAG, "addComment: "+1111);
            addSecondaryComment(edContent, content);
        } else {
            Log.d(TAG, "addComment: "+22222);
            addPrimaryComment(edContent, content);
        }
    }

    //对子评论进行评论
    private void addSecondaryComment(EditText edContent, String content) {
        SendRequest.childCommentAdd(SpUtils.getInstance().getLoadUserBean().getData().getToken(), SpUtils.getInstance().getLoadUserBean().getData().getId(),
                type, typeId, String.valueOf(pId == 0 ? "" : pId), String.valueOf(puId == 0 ? "" : puId), content, new StringCallback() {

                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        if (SpUtils.getInstance().getIsLogin()) {
                            showHideLoading(true);
                        }
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        showHideLoading(false);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        flag = true;
                        mWindowBinding.tvCommentSend.setEnabled(true);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        flag = true;
                        try {
                            CommentReplyBean mCommentReplyBean = GsonUtils.parseJsonToBean(response, CommentReplyBean.class);
                            if (mCommentReplyBean != null && mCommentReplyBean.isSuccess()) {
                                sensorsPoint();
                                edContent.setFocusable(false);
                                edContent.setFocusableInTouchMode(false);
                                mWindowBinding.edContent.setText("");
//                                ToastUtils.showView(WindowAddCommentActivity.this, getLayoutInflater().inflate(R.layout.toast_release_revision, null));
                                try {
                                    CommentReplyBean.DataBean data = mCommentReplyBean.getData();
                                    if (data.getRewardScore() > 0) {
                                        DialogManager.showCoinDialog(WindowAddCommentActivity.this, "评论成功", data.getRewardScore());
                                    }
                                } catch (Exception e) {
                                    e.getMessage();
                                }

                                mIntent.putExtra(CommentConstant.COMMENT_IS_VIOLATION, isShowReply);
                                mIntent.putExtra("replyBean", mCommentReplyBean);
                                mIntent.putExtra(CommentConstant.COMMENT_CONTENT, "");
                                setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
                                finish();
                            } else {
                                if (mCommentReplyBean != null && !TextUtils.isEmpty(mCommentReplyBean.getMsg())) {
                                    ToastUtils.showShort(getApplicationContext(), mCommentReplyBean.getMsg());
                                    mIntent.removeExtra(CommentConstant.COMMENT_IS_VIOLATION);
                                    mIntent.putExtra(CommentConstant.COMMENT_IS_VIOLATION, true);
                                    mIntent.putExtra(CommentConstant.COMMENT_TYPE, type);
                                    mIntent.putExtra(CommentConstant.COMMENT_TYPE_ID, typeId);
                                    mIntent.putExtra(CommentConstant.COMMENT_CONTENT, mWindowBinding.edContent.getText().toString().trim());
                                    setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
                                    finish();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //产生一个主评论
    private void addPrimaryComment(EditText edContent, String content) {
        SendRequest.commentAdd(SpUtils.getInstance().getLoadUserBean().getData().getToken(), SpUtils.getInstance().getLoadUserBean().getData().getId(),
                type, typeId, content, new StringCallback() {

                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        if (SpUtils.getInstance().getIsLogin()) {
                            showHideLoading(true);
                        }
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        showHideLoading(false);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        flag = true;
                        mWindowBinding.tvCommentSend.setEnabled(true);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        flag = true;
                        try {
                            CommentReplyBean mCommentReplyBean = GsonUtils.parseJsonToBean(response, CommentReplyBean.class);
                            if (mCommentReplyBean != null && mCommentReplyBean.isSuccess()) {
                                sensorsPoint();
                                edContent.setFocusable(false);
                                edContent.setFocusableInTouchMode(false);
                                mWindowBinding.edContent.setText("");
                                EventBusUtils.sendNotify(MessageBus.msgid_send_comment_success);
//                                ToastUtils.showView(WindowAddCommentActivity.this, getLayoutInflater().inflate(R.layout.toast_release_revision, null));
                                try {
                                    CommentReplyBean.DataBean data = mCommentReplyBean.getData();
                                    if (data.getRewardScore() > 0) {
                                        //发表评论
                                        DialogManager.showCoinDialog(WindowAddCommentActivity.this, "评论成功", data.getRewardScore());
                                    }
                                } catch (Exception e) {
                                    e.getMessage();
                                }

                                mIntent.putExtra(CommentConstant.COMMENT_IS_VIOLATION, isShowReply);
                                mIntent.putExtra("replyBean", mCommentReplyBean);
                                mIntent.putExtra(CommentConstant.COMMENT_CONTENT, "");
                                setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
                                finish();
                            } else {
                                if (mCommentReplyBean != null && !TextUtils.isEmpty(mCommentReplyBean.getMsg())) {
                                    ToastUtils.showShort(getApplicationContext(), mCommentReplyBean.getMsg());
                                    mIntent.putExtra("isViolation", true);
                                    mIntent.removeExtra(CommentConstant.COMMENT_IS_VIOLATION);
                                    mIntent.putExtra(CommentConstant.COMMENT_TYPE, type);
                                    mIntent.putExtra(CommentConstant.COMMENT_TYPE_ID, typeId);
                                    mIntent.putExtra(CommentConstant.COMMENT_CONTENT, mWindowBinding.edContent.getText().toString().trim());
                                    setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
                                    finish();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void showHideLoading(boolean isShow) {
        if (isShow) {
            Animation antv = AnimationUtils.loadAnimation(WindowAddCommentActivity.this, com.baselibrary.R.anim.loading_progressbar);
            LinearInterpolator lin = new LinearInterpolator();
            antv.setInterpolator(lin);
            antv.setRepeatCount(-1);
            mWindowBinding.progress.startAnimation(antv);
            mWindowBinding.llLoading.setVisibility(View.VISIBLE);
        } else {
            mWindowBinding.llLoading.setVisibility(View.GONE);
        }
    }

    private void initContentView() {
        mWindowBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_comment_window_revision);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = ViewGroup.LayoutParams.FILL_PARENT;
        lp.gravity = Gravity.BOTTOM;
        getWindow().setAttributes(lp);
        mWindowBinding.edContent.setFocusable(true);
        mWindowBinding.edContent.setFocusableInTouchMode(true);
        mWindowBinding.edContent.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        KeyBoardUtils.hideSoftKeyboard(WindowAddCommentActivity.this);
        mIntent.removeExtra(CommentConstant.COMMENT_IS_VIOLATION);
        mIntent.putExtra(CommentConstant.COMMENT_TYPE, type);
        mIntent.putExtra(CommentConstant.COMMENT_TYPE_ID, typeId);
        mIntent.putExtra(CommentConstant.COMMENT_CONTENT, mWindowBinding.edContent.getText().toString().trim());
        setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
        finish();
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            KeyBoardUtils.hideSoftKeyboard(WindowAddCommentActivity.this);
            mIntent.removeExtra(CommentConstant.COMMENT_IS_VIOLATION);
            mIntent.putExtra(CommentConstant.COMMENT_TYPE, type);
            mIntent.putExtra(CommentConstant.COMMENT_TYPE_ID, typeId);
            mIntent.putExtra(CommentConstant.COMMENT_CONTENT, mWindowBinding.edContent.getText().toString().trim());
            setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
            finish();
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    //监听返回键(有软键盘的情况下想直接返回，需要拦截KeyEvent.ACTION_UP事件)
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            mIntent.removeExtra(CommentConstant.COMMENT_IS_VIOLATION);
            mIntent.putExtra(CommentConstant.COMMENT_TYPE, type);
            mIntent.putExtra(CommentConstant.COMMENT_TYPE_ID, typeId);
            mIntent.putExtra(CommentConstant.COMMENT_CONTENT, mWindowBinding.edContent.getText().toString().trim());
            setResult(CommentConstant.COMMENT_RESPONSE, mIntent);
            finish();
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 设置ViewPager表情
     */
    private void initViewPager() {
        EmojiVpAdapter adapter = new EmojiVpAdapter(this);
        mWindowBinding.vpEmoji.setAdapter(adapter);
        //表情点击监听
        adapter.setOnEmojiClickListener(new EmojiVpAdapter.OnEmojiClickListener() {
            @Override
            public void onClick(String emoji) {
                if ("del".equals(emoji)) {
                    //表示点击的是删除按钮
                    KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL);
                    mWindowBinding.edContent.onKeyDown(KeyEvent.KEYCODE_DEL, event); //KeyEvent.KEYCODE_DEL表示退格键

                } else {
                    mWindowBinding.edContent.append(emoji);
                }
            }
        });
        mWindowBinding.vpEmoji.setCurrentItem(0);//预加载页面
        //关联指示器点
        adapter.setupWithPagerPoint(mWindowBinding.vpEmoji, mWindowBinding.llPoint);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        KeyBoardUtils.hideSoftKeyboard(this);
    }


    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(final MessageBus messageBus) {
        if (messageBus.getCodeType().equals(MessageBus.msgId_comment_open)) {
            mCommentEventBusBean = (CommentEventBusBean) messageBus.getMessage();
        }
    }

    private void sensorsPoint() {
        if (mCommentEventBusBean != null) {
            SensorsDataManager.Companion.getInstance().releaseComment(mCommentEventBusBean.getPositionType(), type != 1 ? "评论主内容" : "评论某条评论",
                    mCommentEventBusBean.getCommentPageType(), mWindowBinding.edContent.getText().toString());
        }
    }
}
